package org.asiainfo.im.server.config;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import lombok.RequiredArgsConstructor;
import org.asiainfo.im.server.config.properties.SocketIOProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Optional;

/**
 * socket-io 配置
 *
 * @author dotor-ww
 */
@Configuration
@EnableConfigurationProperties(SocketIOProperties.class)
@RequiredArgsConstructor
public class SocketIOConfig {

    private final SocketIOProperties socketIOProperties;

    /**
     * 注册 SocketIOServer
     *
     * @return socketIOServer
     */
    @Bean
    public SocketIOServer socketIOServer() {
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(socketConfig);
        config.setHostname(socketIOProperties.getHost());
        config.setPort(socketIOProperties.getPort());
        config.setBossThreads(socketIOProperties.getBossCount());
        config.setWorkerThreads(socketIOProperties.getWorkCount());
        config.setAllowCustomRequests(socketIOProperties.getAllowCustomRequests());
        config.setUpgradeTimeout(socketIOProperties.getUpgradeTimeout());
        config.setPingTimeout(socketIOProperties.getPingTimeout());
        config.setPingInterval(socketIOProperties.getPingInterval());
        final SocketIOServer server = new SocketIOServer(config);
        Optional.ofNullable(socketIOProperties.getNamespaces()).ifPresent(nss -> Arrays.stream(nss).forEach(server::addNamespace));
        return server;
    }

    /**
     * 扫描SocketIO注解
     *
     * @return 扫描结果
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner() {
        return new SpringAnnotationScanner(socketIOServer());
    }
}
